package leetcode.code1162;

import java.util.LinkedList;
import java.util.Queue;

import leetcode.IDebug;
import leetcode.helper.H;

public class Solution implements IDebug {

	int[] d = new int[] { 0, -1, 0, 1, -1, 0, 1, 0 };

	public int maxDistance(int[][] grid) {
		int m = grid.length, n = grid[0].length;
		Queue<int[]> queue = new LinkedList<>();
		for (int i = 0; i < m; i++) {
			for (int j = 0; j < n; j++) {
				int cur = grid[i][j];
				if (cur == 1) {
					queue.add(new int[] { i, j });
				}
			}
		}
		int ans = -1;
		if (queue.size() == 0 || queue.size() == m * n) {
			return ans;
		}
		while (!queue.isEmpty()) {
			ans += 1;
			int size = queue.size();
			while (size > 0) {
				int[] cur = queue.poll();
				int x = cur[0], y = cur[1];
				for (int i = 0; i < 8; i += 2) {
					int nextx = x + d[i], nexty = y + d[i + 1];
					if (nextx >= 0 && nextx < m && nexty >= 0 && nexty < n && grid[nextx][nexty] == 0) {
						grid[nextx][nexty] = 1;
						queue.add(new int[] { nextx, nexty });
					}
				}
				size--;
			}
		}
		return ans;
	}

	@Override
	public void debug4() {
		H.compare(2, this.maxDistance(H.str2array1("[[1,0,1],[0,0,0],[1,0,1]]")));
		H.compare(4, this.maxDistance(H.str2array1("[[1,0,0],[0,0,0],[0,0,0]]")));

	}

	@Override
	public void debug3() {
		// TODO Auto-generated method stub

	}

	@Override
	public void debug2() {
		// TODO Auto-generated method stub

	}

	@Override
	public void debug1() {
		// TODO Auto-generated method stub

	}

	public static void main(String[] args) {
		Solution so = new Solution();
		so.debug1();
		so.debug2();
		so.debug3();
		so.debug4();

	}

}
